import requests
import base64
from outexcel import write_excel
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# 账号:  17783621822
# 密码:  830923qq

host = "https://prod-api.huoxingy.com/v1"
xySDK = requests.Session()

def out_huo_login(u,p,logs=None):
    """开始导出"""
    logs.info("[火星捕手] 开始导出商品数据.")
    # xySDK = myYaoRequest(u, p)
    my_cookies = requests.utils.cookiejar_from_dict({}, cookiejar=None, overwrite=True)
    token = base64.b64encode((f"{u}:{p}").encode()).decode()
    headers = {
        "Content-Type":"application/json",
        "Authorization":f"Basic {token}"
    }
    xySDK.cookies = my_cookies
    xySDK.headers = headers
    xySDK.verify = False
    # 登录
    res = xySDK.post(url=f'{host}/admin/login')
    if res.status_code != 200:
        logs.setpath(None)
        logs.warn("[火星捕手] 登录失败...")
        return None
    # print("登录成功")
    # cookies=requests.utils.dict_from_cookiejar(xySDK.cookies)
    # print(cookies)
    # 门店列表
    res = xySDK.get(url=f'{host}/admin/stores')
    if res.status_code != 200:
        logs.setpath(None)
        logs.warn("[火星捕手] 获取门店列表失败...")
        return None
    # print("获取门店列表成功")
    # print(res.json())
    x = [[i["id"],i["name"],i["addr"]] for i in res.json()]
    logs.setPlaces(x)

def out_huo_data(pid, logs=None):
    """开始导出"""
    res = xySDK.post(url=f'{host}/admin/authorize',params={"storeId":pid})
    if res.status_code != 200:
        logs.setpath(None)
        logs.wran("[火星捕手] 选择门店名称失败...")
        return None

    res = xySDK.get(url=f'{host}/admin/get-ps',params={"storeId":pid})
    if res.status_code != 200:
        logs.setpath(None)
        logs.wran("[火星捕手] 加载商品列表失败...")
        return None
    # print(res.json())
    r = [{
        "name":i["name"],
        "tag":i["typeName"],
        "cprice":i["costPrice"],
        "sprice":i["salesPrice"],
        "stock":i["quantity"],
        "code":"",
        } for i in res.json()]
    logs.info("[火星捕手] 开始导出数据...")
    f = write_excel(r)
    # f = "text.xml"
    logs.setpath(f)
    logs.info(f"[火星捕手] 任务完成 {f}")